<template>
	<view>
		<view class="content">
			<view class="list">
				<view class="empty" v-if="addressList.length == 0">
					<image class="img" mode="widthFix" src="/static/empty/empty-address.png"></image>
					<text class="text">暂无收货地址</text>
					<!-- <view class="btn" @tap="add">
						新增地址
					</view> -->
					<button class="btn" @tap="add" :plain="true">新增地址</button>
				</view>
				<uni-slideview v-else>
					<!-- key值设为唯一动态变量，省去子组件watch监听，实现子组件伴随数据加载重新刷新 -->
					<uni-slideview-item :options="optionsFormat(item.isDefault)" v-for="(item,index) in addressList" :key="indexFormat(index)"
					 @click="slideClick($event,index)">
						<view class="list-item" @click.stop="select(index)">
							<view class="selected-box" v-if="selectFormat(item.id)">
								<text class="selected"></text>
							</view>
							<view class="item-left">
								<view class="name-tel">
									<view class="name">{{item.name}}</view>
									<view class="tel num-font">{{item.telephone}}</view>
									<view class="tip" v-if="item.isDefault">默认</view>
								</view>
								<view class="address">
									<text>{{item.province}}{{item.city}}{{item.district}} {{item.street1}}</text>
								</view>
							</view>
							<view class="item-right" @tap.stop="edit(index)">
								<view class="yticon img">
									<image src="/static/img/user/bianji.png" mode="widthFix"></image>
								</view>
							</view>
						</view>
					</uni-slideview-item>
				</uni-slideview>
			</view>
		</view>
		<view class="add" v-if="addressList.length>0">
			<button class="btn" @tap="add">
				<text class="yticon icon-jia2"></text>
				<text>新增地址</text>
			</button>
		</view>
	</view>
</template>
<script>
	import Api from '@/common/api';
	import uniSlideview from '@/components/uni-swipe-action/uni-swipe-action.vue';
	import uniSlideviewItem from '@/components/uni-swipe-action-item/uni-swipe-action-item.vue';

	const SWIPERACTION = {
		'设为默认': 0,
		'删除': 1
	};
	export default {
		components: {
			uniSlideview,
			uniSlideviewItem
		},
		data() {
			return {
				isSelect: false,
				addressList: [],
				slideviewOptions: [{
						text: '设为默认',
						style: {
							backgroundColor: '#e8e8e8',
							color: '#232323'
						}
					},
					{
						text: '删除',
						style: {
							backgroundImage: `linear-gradient(to bottom , #FF0000, #ff5c5c)`
						}
					}
				]
			}
		},
		computed: {
			optionsFormat() {
				return (isDefault) => {
					let slideviewOptions = this.slideviewOptions.concat();
					if (isDefault) {
						slideviewOptions.shift();
					}
					return slideviewOptions
				}
			},
			indexFormat() {
				return (index) => {
					return new Date().getTime() + index
				}
			},
			selectFormat(){
				return (id)=>{
					let selectAddress =  uni.getStorageSync('selectAddress');
					if(selectAddress && this.isSelect){
						return id == selectAddress.id;
					}else{
						return false;
					}
				}
			}
		},
		onShow() {
			this.loadData();
			// uni.getStorage({
			// 	key: 'delAddress',
			// 	success: (e) => {
			// 		let len = this.addressList.length;
			// 		console.log(e)
			// 		if (e.data.hasOwnProperty('id')) {
			// 			for (let i = 0; i < len; i++) {
			// 				if (this.addressList[i].id == e.data.id) {
			// 					this.addressList.splice(i, 1);
			// 					break;
			// 				}
			// 			}
			// 		}
			// 		uni.removeStorage({
			// 			key: 'delAddress'
			// 		})
			// 	}
			// })
			uni.getStorage({
				key: 'saveAddress',
				success: (e) => {
					let len = this.addressList.length;
					console.log(e)
					if (e.data.hasOwnProperty('id')) {
						for (let i = 0; i < len; i++) {
							if (this.addressList[i].id == e.data.id) {
								this.addressList.splice(i, 1, e.data);
								break;
							}
						}
					} else {
						let lastid = this.addressList[len - 1];
						lastid++;
						e.data.id = lastid;
						this.addressList.push(e.data);
					}
					uni.removeStorage({
						key: 'saveAddress'
					})
				}
			})
			
			// uni.getStorage({
			// 	key: "selectAddress",
			// 	success:(e)=>{
			// 		if(e.data.id)
			// 	}
			// })
		},
		onLoad(e) {
			if (e.type == 'select') {
				this.isSelect = true;
			}
		},
		methods: {
			async loadData() {
				let params = {}, data = await Api.apiCall('post', Api.goods.listAddress, params);
				if (data) {
					data.forEach(item => {
						item.mobile = item.telephone;
						item.telephone = item.telephone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
						item.region = {
							"label": `${item.province}-${item.city}-${item.district}`,
							"value": item.cityValue ? item.cityValue.split(',').map(e => Number(e)) : null,
							"cityCode": item.cityCode
						};
						item.isDefault = item.is_default == 1;
					});
					this.addressList = data;
				}
				this.$forceUpdate();
			},
			slideClick(e, index) {
				let id = this.addressList[index].id;
				switch (SWIPERACTION[e.content.text]) {
					case 0: //设为默认
						this.setDefaultAddress(index, id);
						break;
					case 1: //删除
						this.deleteAddress(index, id);
						break;
				}
			},
			edit(index) {
				uni.setStorage({
					key: 'address',
					data: this.addressList[index],
					success: () => {
						uni.navigateTo({
							url: "/pages/user/addressEdit?type=edit"
						})
					}
				});
			},
			async deleteAddress(index, id) {
				let params = {
						'id': id
					},
					data = await Api.apiCall('DELETE', Api.goods.address, params);
				if (data) {
					let selectAddress = uni.getStorageSync('selectAddress');
					uni.removeStorageSync('selectAddress');
					this.addressList.splice(index, 1);
					if(selectAddress.id == id){ //如果删除项为已选择项
						if(this.addressList.length > 0 && this.addressList.some(e => e.isDefault)){ //如果当前列表存在默认地址
							uni.setStorageSync('selectAddress', this.addressList[this.addressList.findIndex(e => e.isDefault)]) //将默认地址储存为已选择地址
						}else{
							uni.setStorageSync('selectAddress', this.addressList[0]) //如果当前列表不存在默认地址，则将列表第一项储存为已选择地址
						}
					}
				}
			},
			async setDefaultAddress(index, id) {
				let params = {
						'id': id,
						'is_default': true
					},
					data = await Api.apiCall('PUT', Api.goods.address, params);
				if (data) {
					this.addressList.forEach(e => {
						e.isDefault = e.id == id;
					});
					let index = this.addressList.findIndex(e => uni.getStorageSync('selectAddress').id == e.id); 
					uni.setStorageSync('selectAddress', this.addressList[index])
				}
			},
			add() {
				uni.navigateTo({
					url: "/pages/user/addressEdit?type=add"
				})
			},
			select(index) {
				//是否需要返回地址(从订单确认页跳过来选收货地址)
				if (!this.isSelect) {
					return;
				}
				uni.setStorage({
					key: 'selectAddress',
					data: this.addressList[index],
					success() {
						uni.navigateBack();
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FFF;
	}

	.icon {
		// &.bianji {
		// 	&:before{content:"\e61b";}
		// }
		// &.tianjia {
		// 	&:before{content:"\e81a";}
		// }
	}

	.selected-box {
		display: flex;
		align-items: center;
		margin-right: 20upx;
		.selected {
			width: 30upx;
			height: 30upx;
			position: relative;
			border-radius: 50%;
			box-sizing: border-box;
			display: flex;
			justify-content: center;
			align-items: center;
			overflow: hidden;

			background-color: #FFBC21;
			border-color: #FFBC21;
			box-shadow: 0 3upx 8upx #FFBC21;

			&::before {
				font: normal normal normal 14px/1 uni;
				content: "\EA08";
				color: #fff;
				font-size: 14px;
				transform: scale(.6);
			}
		}
	}

	.add {
		position: fixed;
		bottom: 0;
		width: 100vw;
		height: 120upx;
		display: flex;
		justify-content: center;
		align-items: center;

		.btn {
			// box-shadow: 0upx 5upx 10upx rgba(0, 0, 0, 0.4);
			width: 80vw;
			height: 80upx;
			border-radius: 40upx;
			background-color: #FFBC21;
			color: #FFF;
			display: flex;
			justify-content: center;
			align-items: center;

			.icon {
				height: 80upx;
				color: #232323;
				font-size: 30upx;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			font-size: 30upx;
		}
	}

	.list {
		width: 100vw;

		.empty {
			width: 100%;
			margin-top: 178upx;
			padding: 0 30upx;
			display: flex;
			flex-flow: column wrap;
			justify-content: center;
			align-items: center;

			.img {
				width: 356upx;
				height: 334upx;
			}

			.text {
				margin-top: 24upx;
				font-size: 24upx;
				color: #ABADAD;
			}

			.btn {
				width: 250upx;
				height: 88upx;
				margin-top: 60upx;
				border-radius: 44upx;
				border: 1upx solid #757677;
			}
		}

		.list-item {
			width: 100vw;
			padding: 25upx 20upx;
			background-color: #FFFFFF;
			position: relative;
			box-sizing: border-box;
			display: flex;
			flex-flow: row nowrap;

			&::before {
				content: '';
				height: .5upx;
				background-color: $uni-border-color;
				width: calc(100vw - 20upx);
				position: absolute;
				bottom: 0;
				right: 0;
			}

			.item-left {
				flex: 1;
				flex-wrap: wrap;
				position: relative;

				.name-tel {
					display: inline-flex;
					align-items: center;
					font-size: 30upx;
					color: #313332;

					.name {
						font-weight: 500;
					}

					.tel {
						margin: 0 20upx 0 40upx;
					}

					.tip {
						display: inline-flex;
						justify-content: center;
						align-items: center;
						border-radius: 5upx;
						width: 55upx;
						height: 30upx;
						font-size: 20upx;
						color: #FFBC21;
						background-color: rgba(255, 188, 33, .3);
					}
				}

				.address {
					width: 100%;
					font-size: 24upx;
					color: #232323;
					font-weight: 300;
					margin-top: 10upx;

					.detailed {
						margin-left: 20upx;
					}
				}
			}

			.item-right {
				flex: 0 0 60upx;
				position: relative;

				.yticon {
					position: absolute;
					right: 0;
					top: 55upx;
					width: 32upx;
					height: 32upx;
					color: #777;

					image {
						width: 100%;
						height: auto;
					}
				}

			}
		}
	}
</style>
